package com.aikg.kgrag_java.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    private final String serverUrl = "http://192.168.24.128:9200"; // Elasticsearch 服务器的 URL

    // 创建 RestClient Bean
    @Bean
    public RestClient restClient() {
        return RestClient
                .builder(HttpHost.create(serverUrl))
                .build();
    }

    // 创建 ElasticsearchTransport Bean
    @Bean
    public ElasticsearchTransport elasticsearchTransport(RestClient restClient) {
        // 使用 JacksonJsonpMapper 来处理 JSON 数据的序列化和反序列化
        JsonpMapper jsonpMapper = new JacksonJsonpMapper();
        return new RestClientTransport(restClient, jsonpMapper);
    }

    // 创建 ElasticsearchClient Bean
    @Bean
    public ElasticsearchClient elasticsearchClient(ElasticsearchTransport elasticsearchTransport) {
        return new ElasticsearchClient(elasticsearchTransport);
    }

    @Bean
    public ElasticsearchAsyncClient elasticsearchAsyncClient(RestClient restClient) {
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchAsyncClient(transport);
    }

}
